package com.spgf.controller;

import java.text.NumberFormat;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.archtecture.model.exceptions.NegocioException;
import com.archtecture.model.patterns.PadraoActivityMnt;
import com.archtecture.model.patterns.PadraoRNAb;
import com.spgf.model.entities.LancamentoModel;
import com.spgf.model.enums.Mes;
import com.spgf.model.rn.LancamentoRN;
import com.spgf.view.utils.AdapterListViewDespesas;
import com.spgf.view.utils.DialogManutencao;

public class DespesaMntActivity extends PadraoActivityMnt<LancamentoModel> {

	private ListView listview;

	private TextView txtTotal;

	private List<LancamentoModel> listaModel;

	@SuppressLint("SimpleDateFormat")
	public void atualizarLista() throws NegocioException {

		listaModel = null;

		Double valorTotal = 0.0;
		for (final LancamentoModel l : getListaModel()) {
			valorTotal += l.getValor();
		}

		listview.setAdapter(new AdapterListViewDespesas(this, getListaModel()));

		txtTotal.setText(NumberFormat.getCurrencyInstance().format(valorTotal));
	}

	@Override
	protected void construirTela(Bundle savedInstanceState)
			throws NegocioException {
		setContentView(R.layout.activity_despesa_mnt);

		listview = (ListView) findViewById(R.id.lst_despesa_mnt_resultado);
		listview.setScrollbarFadingEnabled(true);
		listview.setOnItemLongClickListener(this);

		txtTotal = (TextView) findViewById(R.id.lbl_despesa_mnt_valor_total);
		txtTotal.setText(NumberFormat.getCurrencyInstance().format(0D));

		// Mes lMes = Mes.values()[Calendar.getInstance().get(Calendar.MONTH)];
		// String lMesAno = lMes.getNome() + " / " +
		// Calendar.getInstance().get(Calendar.YEAR);
		// ((TextView)
		// findViewById(R.id.txt_despesa_mnt_titulo)).setText(lMesAno);

		atualizarLista();

	};

	protected boolean executarLongClick(AdapterView<?> pParent, View pView,
			int pPosition, long pID) throws NegocioException {

		if (pParent.getId() == R.id.lst_despesa_mnt_resultado) {

			new DialogManutencao(this, getListaModel().get(pPosition)).show();
			return true;
		}

		return false;

	}

	public List<LancamentoModel> getListaModel() throws NegocioException {

		if (listaModel == null) {

			final LancamentoModel lancamento = new LancamentoModel();

			final Calendar cal = Calendar.getInstance();
			lancamento.setData(cal.getTime());

			listaModel = new LancamentoRN(this).obterLancamentosPorMes(Mes
					.getEnum(cal.get(Calendar.MONTH)));
		}

		return listaModel;
	}

	@Override
	public Class getControleCadastro() {
		return DespesaCadActivity.class;
	}

	@Override
	protected PadraoRNAb<LancamentoModel> getRN() {
		return new LancamentoRN(this);
	}
}
